# coding=utf-8
"""
微信机器人，定时发送消息
"""
from time import time
from datetime import datetime

import sched
from apscheduler.schedulers.background import BackgroundScheduler
import itchat
import requests
import json
from utils.const_value import API, KEY, UNIT, LANGUAGE
from utils.helper import getLocation


username_list = ['GX', 'YZW']

# @sched.scheduled_job('cron', id='my_job_id', day='last sun')
def task():
    print('Task begin: %s' % datetime.now())
    msg = get_weather()
    for item in username_list:
        users = itchat.search_friends(name=item)
        user_name = users[0]['UserName']
        itchat.send(u''+msg, user_name)  # filehelper


# Wechat listener
@itchat.msg_register(itchat.content.TEXT)
def print_content(msg):
    text = msg['Text']
    print(text)
    if text == '天气':
        return get_weather()
    return text


def fetch_weather(location):
    result = requests.get(API, params={
        'key': KEY,
        'location': location,
        'language': LANGUAGE,
        'unit': UNIT
    }, timeout=1)
    return result.text


def format_weather(text):
    print(text)
    obj = json.loads(text)
    location = obj['results'][0]['location']
    daily = obj['results'][0]['daily']
    res = "[太阳] 早安 {} {}\n[玫瑰] {}转{} {}° ~ {}°"
    res = res.format(
        daily[0]['date'],
        get_week_day(datetime.now()),
        daily[0]['text_day'],
        daily[0]['text_night'],
        daily[0]['low'],
        daily[0]['high']
    )
    return res


def get_weather():
    location = getLocation()
    result = fetch_weather(location)
    return format_weather(result)


def get_week_day(date):
    week_day_dict = {
        0: '周一',
        1: '周二',
        2: '周三',
        3: '周四',
        4: '周五',
        5: '周六',
        6: '周日',
    }
    day = date.weekday()
    return week_day_dict[day]


if __name__ == '__main__':
    # Wechat login
    itchat.auto_login(hotReload=True, enableCmdQR=True)

    # Add jobs
    scheduler = BackgroundScheduler()
    scheduler.add_job(task, 'cron', minute=5, hour=7, day_of_week='mon-fri')
    # scheduler.add_job(task, 'cron', second='*/5')

    try:
        scheduler.start()
        print('Scheduler running')
        itchat.run()
        print('ItChat running')
    except (KeyboardInterrupt, SystemExit):
        print('Scheduler shutdown')
        scheduler.shutdown()
